package day03;

import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.SlidingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import untils.UserBehavior;
import untils.itemViewCountPerWindow;

import java.time.Duration;

/**
 * 实现每隔5分钟统计过去一小时的指标
 * 指标 : 每个商品在每个窗口的访问次数
 * 使用累加器的思想优化程序
 */
public class Example5 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .readTextFile("D:\\atguigu\\flinkdata\\src\\main\\resources\\UserBehavior.csv")
                .map(new MapFunction<String, UserBehavior>() {
                    @Override
                    public UserBehavior map(String s) throws Exception {
                        String[] arr = s.split(",");
                        return new UserBehavior(
                                arr[0],arr[1],arr[2],arr[3],Long.parseLong(arr[4]) * 1000L
                        );
                    }
                })
                //筛选浏览的窗口
                .filter(r -> r.type.equals("pv"))
                //指定时间戳
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<UserBehavior>forBoundedOutOfOrderness(Duration.ofSeconds(0))
                        .withTimestampAssigner(new SerializableTimestampAssigner<UserBehavior>() {
                            @Override
                            public long extractTimestamp(UserBehavior userBehavior, long l) {
                                return userBehavior.ts;
                            }
                        })
                )
                //按照商品ID进行分区
                .keyBy(r -> r.itemId)
                //每隔5分钟开启一个持续一小时的窗口
                .window(SlidingEventTimeWindows.of(Time.hours(1),Time.minutes(5)))
                //当窗口关闭时触发
                .aggregate(new AggregateFunction<UserBehavior, Long, Long>() {

                    @Override
                    public Long createAccumulator() {
                        return 0L;
                    }

                    @Override
                    public Long add(UserBehavior value, Long accumulator) {
                        return accumulator + 1L;
                    }

                    @Override
                    public Long getResult(Long accumulator) {
                        return accumulator;
                    }

                    @Override
                    public Long merge(Long a, Long b) {
                        return null;
                    }
                }, new ProcessWindowFunction<Long, itemViewCountPerWindow, String, TimeWindow>() {

                    @Override
                    public void process(String s, Context context, Iterable<Long> elements, Collector<itemViewCountPerWindow> out) throws Exception {
                        out.collect(new itemViewCountPerWindow(
                                s,
                                elements.iterator().next(), // 将迭代器中唯一的元素，也就是getResult的结果取出
                                context.window().getStart(),
                                context.window().getEnd()
                        ));
                    }
                })
                .print();
        env.execute();
    }
}
